import request from '@/utils/request'

// 体育彩票API基础配置
const SPORTTERY_BASE_URL = 'https://webapi.sporttery.cn/gateway/uniform/football'

// 获取赛事列表
export function fetchSportteryMatches(params = {}) {
  return request({
    url: `${SPORTTERY_BASE_URL}/getMatchCalculatorV1.qry`,
    method: 'get',
    params: Object.assign({
      poolCode: '',
      channel: 'c'
    }, params)
  })
}

// 获取联赛列表
export function fetchSportteryLeagues() {
  return request({
    url: `${SPORTTERY_BASE_URL}/getLeagueListV1.qry`,
    method: 'get',
    params: {
      channel: 'c'
    }
  })
}

// 获取赔率信息
export function fetchSportteryOdds(matchId) {
  return request({
    url: `${SPORTTERY_BASE_URL}/getOddsV1.qry`,
    method: 'get',
    params: {
      matchId,
      channel: 'c'
    }
  })
}

// 获取比赛详情
export function fetchSportteryMatchDetail(matchId) {
  return request({
    url: `${SPORTTERY_BASE_URL}/getMatchDetailV1.qry`,
    method: 'get',
    params: {
      matchId,
      channel: 'c'
    }
  })
}

// 同步体彩数据到本地数据库
export function syncSportteryData() {
  return request({
    url: '/api/match/sync-sporttery',
    method: 'post'
  })
}

// 解析体彩数据
export function parseSportteryData(sportteryData) {
  const matches = []

  if (sportteryData && sportteryData.value && sportteryData.value.matchInfo) {
    sportteryData.value.matchInfo.forEach(match => {
      const parsedMatch = {
        id: match.matchId,
        league: match.leagueName || '未知联赛',
        home_team: match.homeTeamName || '主队',
        away_team: match.awayTeamName || '客队',
        match_time: match.matchTime || new Date().toISOString(),
        status: getMatchStatus(match.matchStatus),
        win_odds: match.spf ? parseFloat(match.spf.win) : 0,
        draw_odds: match.spf ? parseFloat(match.spf.draw) : 0,
        lose_odds: match.spf ? parseFloat(match.spf.lose) : 0,
        sporttery_id: match.matchId,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      }
      matches.push(parsedMatch)
    })
  }

  return matches
}

// 获取比赛状态
function getMatchStatus(status) {
  const statusMap = {
    '0': 'upcoming', // 未开始
    '1': 'live', // 进行中
    '2': 'finished', // 已结束
    '3': 'cancelled' // 已取消
  }
  return statusMap[status] || 'upcoming'
}
